package com.bw.property.vm

import androidx.lifecycle.viewModelScope
import com.bw.common.vm.BaseViewModel
import com.bw.property.entity.ParkValue
import com.bw.property.intent.ParkViewIntent
import com.bw.property.module.ParkApplyRepository
import com.bw.property.state.ParkUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ParkViewModel @Inject constructor(private val repository:ParkApplyRepository):BaseViewModel<ParkViewIntent>() {


        private val _uiState = MutableStateFlow<ParkUiState>(ParkUiState.NoneState)
        val uiState:StateFlow<ParkUiState> = _uiState.asStateFlow()

        override fun dispatchIntent(intent: ParkViewIntent) {
            when(intent){
                is ParkViewIntent.LoadParkList->loadParkList()
                else->{}
            }
        }

        private fun loadParkList(){
            viewModelScope.launch(Dispatchers.IO) {
                try {
                    var result = repository.getParkApplyList()
                    if(result.statusCode=="200"){
                        var parkList = mutableListOf<ParkValue>()
                        parkList.addAll(result.getValues())
                        _uiState.value = ParkUiState.LoadParkListSuccess(result.getValues())
                    }else{
                        _uiState.value = ParkUiState.LoadParkListFail(result.msg)
                    }
                }catch (e:Exception){
                    e.printStackTrace()
                    _uiState.value = ParkUiState.LoadParkListSuccess("请联系客服")
                }finally {
                    cancel()
                }
            }
        }

    }